package com.kuang.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * Author: Zhang Dongwei
 * Date: 2022/3/16 14:11
 * 求和计算的任务
 * 如何使用forkjoin
 * 1. forkjoinpool 通过它来执行
 * 2. 计算任务 forkjoinpool.execute(ForkJoinTask task)
 * 3. 计算类要继承ForkJoinTask
 */
public class ForkJoinDemo extends RecursiveTask<Long> {
    private Long start; // 1
    private Long end;  // 1990900000
    // 临界值，如果超过就会拆成两个任务
    private Long temp = 10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    // 计算方法
    @Override
    protected Long compute() {
        if((end-start)<temp){ //如果大于10000就分支合并计算
            Long sum = 0L;
            for(Long i = start; i<end; i++) {
                sum += i;
            }
            return sum;
        }else {// forkjoin
            long middle = (start + end)/2; // 中间值
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            task1.fork(); // 拆分任务，把任务压入线程队列
            ForkJoinDemo task2 = new ForkJoinDemo(middle+1, end);
            task2.fork(); // 拆分任务，把任务压入线程队列
            return task1.join() + task2.join();
        }
    }
}
